package com.lemote.interceptor;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.lemote.entity.User;
import com.lemote.utils.Constant;

/**
 * 
 * 拦截器。验证用户是否具有权限
 * @author slaton.wu@gmail.com
 * @version 1.0
 * @created 2011-6-12 下午06:43:49
 */
@Component("permissionInterceptor")
public class PermissionInterceptor implements Filter {

	private HttpSession session;
	
	public void destroy() {
		
		if (session!=null) {
			session.removeAttribute(Constant.SESSION_USER);
		}
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		 HttpServletRequest request = (HttpServletRequest)req;
		this.session = request.getSession();
		if(verify(request)){
			((HttpServletResponse)resp).sendRedirect(request.getContextPath()+"/user/login.htm");
			return ;
		}
		chain.doFilter(req, resp);
	}

	public void init(FilterConfig config) throws ServletException {
	
	}
	
	public Boolean verify(HttpServletRequest request){
		User user = (User) session.getAttribute(Constant.SESSION_USER);
		String uri = request.getRequestURI();
		if (StringUtils.contains(uri, "login.htm")||StringUtils.contains(uri, "loginUser.htm")||user!=null||StringUtils.contains(uri, "code.htm")) {
			return false;
		}
		return true;
	}

}
